package com.topvision.controller.ar;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.topvision.util.*;
import com.topvision.util.ftp.FtpUtil;
import com.topvision.util.ftp.SFTPUpload;
import com.topvision.utils.ftp.FtpConfigUtil;
import com.topvision.xss.XssHttpServletRequestWrapper;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topvision.model.ar.ArFace;
import com.topvision.service.ar.ArFaceService;
import com.topvision.controller.AbstractController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

/**
 * 人脸识别
 *
 * @author shengwm
 * @email 179653076@qq.com
 * @date 2017-10-10 16:12:34
 */
@RestController
@RequestMapping("ar/arface")
public class ArFaceController extends AbstractController {
    @Autowired
    private ArFaceService arFaceService;

    @Value("#{APP_PROP['face.app.key']}")
    private String appKey;


    @Value("#{APP_PROP['face.app.secret']}")
    private  String appSecret;

    @Value("#{APP_PROP['face.app.url']}")
    private  String appUrl;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("ar/arface:list")
    public R list(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);

        List<ArFace> arFaceList = arFaceService.queryList(query);
        int total = arFaceService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(arFaceList, total, query.getLimit(), query.getPage());

        return R.success().put("page", pageUtil);
    }

    @RequestMapping("/findListByParam")
    @RequiresPermissions("ar/arface:list")
    public R findListByParam(@RequestParam Map<String, Object> params){

        List<ArFace> arFaceList = arFaceService.queryByParam(params);

        return R.success().put("arFaceList", arFaceList);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("ar/arface:info")
    public R info(@PathVariable("id") Long id){
        ArFace arFace = arFaceService.queryObject(id);
        return R.success().put("arFace", arFace);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("ar/arface:save")
    public R save(HttpServletRequest request){
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        InputStream inputStream = null;
        // 文件类型
        String type=null;
        String fileName=null;
        MultipartHttpServletRequest multiRequest = null;
        ArFace arFace = new ArFace();
        if (request instanceof MultipartHttpServletRequest) {
             multiRequest = (MultipartHttpServletRequest) request;
            try {
                inputStream = multiRequest.getFile("file").getInputStream();
                fileName = multiRequest.getFile("file").getOriginalFilename();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
        LocalDate today = LocalDate.now();
        String dir = today.toString().replace("-","/");
        String filename = String.valueOf(System.currentTimeMillis());
        String name = type != null?filename+"."+type:filename+".jpg";
        FtpConfigUtil.initFtp();
        try {
            FtpUtil.upload(inputStream,name, Const.FTP_FACE_BASE_DIR+dir);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String imgUrl= Const.FTP_IMG_BASE_URL+"face/"+dir+"/"+name;
        //组织人脸库请求API
        Map<String,Object> map = new LinkedHashMap<>();
        File file = null;
        if (StringUtils.isNotBlank(multiRequest.getParameter("groupcode"))){
            map.put("groupId",multiRequest.getParameter("groupcode"));
            arFace.setGroupCode(multiRequest.getParameter("groupcode"));
        }
        if (StringUtils.isNotBlank(multiRequest.getParameter("facecode"))){
            map.put("faceId",multiRequest.getParameter("facecode"));
            arFace.setCode(multiRequest.getParameter("facecode"));
        }


        File f = null;
        try {
            f = multipartToFile(multiRequest.getFile("file"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        map.put("img",f);
        if (StringUtils.isNotBlank(multiRequest.getParameter("desc"))){
            map.put("tag",multiRequest.getParameter("desc"));
            arFace.setDesc(multiRequest.getParameter("desc"));
        }


        JSONObject jsonObject = FaceApiUtil.addFace(map);
        String resultcode = jsonObject.get("result_code").toString();
        logger.info(resultcode);
        String resultCode = jsonObject.get("result_code").toString();
        if (Integer.valueOf(resultCode) == 0){
            arFace.setImgUrl(imgUrl);
            arFaceService.save(arFace);
            return R.success();
        }else {
            return R.error().setMsg("人脸服务器开小差啦...");
        }

    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("ar/arface:update")
    public R update(@RequestBody ArFace arFace){
		arFaceService.update(arFace);
        return R.success();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("ar/arface:delete")
    public R delete(@RequestBody Long[] ids){
        ArFace arFace = arFaceService.queryObject(ids[0]);
        Map<String,Object> parammap = new LinkedHashMap<>();
        parammap.put("groupId",arFace.getGroupCode());
        parammap.put("faceId",arFace.getCode());
        JSONObject jsonObject = FaceApiUtil.delFace(parammap);
        String resultcode = jsonObject.get("result_code").toString();
        logger.info(resultcode);
        if (Integer.valueOf(jsonObject.get("result_code").toString()) == 0) {

            String imgUrl = arFace.getImgUrl();
            if (imgUrl != null){
                imgUrl = imgUrl.replace(Const.FTP_IMG_BASE_URL+"face/",Const.FTP_FACE_BASE_DIR);
                String[] strings = imgUrl.split("/");
                String filename = strings[strings.length-1];
                String dir = imgUrl.replace("/"+filename,"");
                FtpConfigUtil.initFtp();
                try {
                    FtpUtil.delete(dir,filename);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            arFaceService.deleteBatch(ids);
            return R.success();
        }else {
            return R.error().setMsg("人脸服务器开小差啦...");
        }
    }

    /**
     * MultipartFile 转换成File
     *
     * @param multfile 原文件类型
     * @return File
     * @throws IOException
     */
    public File multipartToFile(MultipartFile multfile) throws IOException {
        CommonsMultipartFile cf = (CommonsMultipartFile)multfile;
        //这个myfile是MultipartFile的
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File file = fi.getStoreLocation();
        String name =  FilenameUtils.getExtension(fi.getName());
        //手动创建临时文件
        if(file.length() /1024 < 3*1024){
            File tmpFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") +
                    file.getName().replace("tmp",name));
            multfile.transferTo(tmpFile);
            return tmpFile;
        }
        return file;
    }



}
